<template>
    <div class="update-name-container">
        <!-- 导航 -->
        <van-nav-bar
            title="修改昵称"
            left-text="取消"
            right-text="完成"
            @click-left="$emit('close')"
            @click-right="onConfirm"
        />
        <!-- 导航 -->
        <!-- 输入框 -->
        <div class="field-wrap">
            <van-field
                v-model="localName"
                autosize
                type="textarea"
                maxlength="7"
                placeholder="请输入修改的昵称"
                show-word-limit
            />
        </div>
        <!-- 输入框 -->
    </div>
</template>

<script>
import { editUserProfile } from '@/api/user'
    export default {
        name: 'updateName',
        props:{
            userName:{
                type: String,
                required: true
            },
            // value:{
            //     type: String,
            //     required: true
            // }
        },
        data() {
            return {
                localName: this.userName, //输入框的内容
                // localName: this.vlaue, //输入框的内容
            }
        },
        methods: {
            async onConfirm(){
                this.$toast.loading({
                    message: '保存中...',
                    forbidclick: true //禁止点击背景
                })
                try {
                    await editUserProfile({
                        name : this.localName
                    }) 

                    this.$toast.success('修改成功')
                    // 修改成功更新组件的name -> 关闭弹框
                    this.$emit('update-name', this.localName)
                    // this.$emit('input', this.localName)
                    this.$emit('close')
                } catch (err) {
                    if(err && err.response && err.response.status === 409){
                        this.$toast.fail('此用户名已经存在')
                    }
                }
            }
        },
    }
</script>

<style lang="less" scoped>
.field-wrap{
    padding: 14px;
}
</style>